package com.redijedi.tapestry.internal.pagedlist;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Provides an {@link java.util.Iterable} implementation that will only iterate
 * over the objects within the range provided when prepare() is called.
 * 
 * @author torr
 * 
 */
public class PagedSource<T> implements Iterable<T> {

	private List<T> _source = new ArrayList<T>();

	private List<T> _pageSource = new ArrayList<T>();

	private Integer _iterableSize;

	public PagedSource(Iterable<T> source) {
		Iterator<T> i = source.iterator();
		while (i.hasNext()) {
			_source.add(i.next());
		}
		System.out.println("Paging");
	}

	/**
	 * @return
	 * @see java.lang.Iterable#iterator()
	 */
	public Iterator<T> iterator() {
		return _pageSource.iterator();
	}

	public int getTotalRowCount() {
		if (_iterableSize != null) {
			return _iterableSize.intValue();
		}

		_iterableSize = 0;

		Iterator<?> it = _source.iterator();
		while (it.hasNext()) {
			it.next();
			_iterableSize++;
		}

		return _iterableSize.intValue();
	}

	public void prepare(int startIndex, int endIndex) {
		for (int i = startIndex; i <= endIndex; i++) {
			_pageSource.add(_source.get(i));
		}
	}

}
